package com.easygoods.tasks;

import com.bestvike.stone.spring.page.PageableRequest;
import com.easygoods.dao.MemberInfoDao;
import com.easygoods.service.ConfigService;
import com.easygoods.service.PointService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by 许崇雷 on 2019-01-21.
 */
@Component
@CommonsLog
public class PointExpiredScheduling {
    private static final int PAGE_SIZE = 50;

    @Autowired
    private MemberInfoDao memberInfoDao;
    @Autowired
    private PointService pointService;
    @Autowired
    private ConfigService configService;

    //每天 0 点执行  秒 分 时 日 月 周
    @Scheduled(cron = "0 0 1 * * ?")
    public void expirePoints() {
        log.info("=======开始批量积分过期");
        PageableRequest request = new PageableRequest();
        request.setPageSize(PAGE_SIZE);
        request.setPageNum(1);
        List<String> memberIdList = this.memberInfoDao.getMemberIdList(request.toRowBounds());
        while (memberIdList.size() > 0) {
            for (String memberId : memberIdList) {
                try {
                    log.info("=======开始积分过期 memberId:" + memberId);
                    this.pointService.expirePoint(memberId, this.configService.getPointKeepYears());
                    log.info("=======积分过期完成 memberId:" + memberId);
                } catch (Exception e) {
                    log.error("积分过期失败 memberId:" + memberId, e);
                }
            }

            request.setPageNum(request.getPageNum() + 1);
            memberIdList = this.memberInfoDao.getMemberIdList(request.toRowBounds());
        }
        log.info("=======批量积分过期完成");
    }
}
